package com.twxm.breed.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.twxm.breed.entity.FishPond;
import com.twxm.breed.service.*;
import com.twxm.breed.util.Base64Util;
import com.twxm.breed.util.UploadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.twxm.breed.util.ExcelAnalyzeUtil.excelAnalyze;

@RestController
@RequestMapping("/pond")
@Slf4j
public class PondController {
    @Autowired
    private LoginInfoService loginInfoService;

    @Autowired
    private FishPondService fishPondService;
    @Autowired
    private DissolvedOxygenService dissolvedOxygenService;
    @Autowired
    private WaterFactorService waterFactorService;
    @Autowired
    private WeatherFactorService weatherFactorService;
    @Autowired
    private DeviceInfoService deviceInfoService;


    @PostMapping("/create_pond")
    public JSONObject createPond(@RequestParam(value = "userid") String userId,
                                 @RequestParam(value = "pondid") String pondId,
                                 @RequestParam(value = "square") float square,
                                 @RequestParam(value = "waterdepth") float waterDepth,
                                 @RequestParam(value = "soil") String soil,
                                 @RequestParam(value = "bottomtype") String bottomType,
                                 @RequestParam(value = "image") MultipartFile file) {
        log.info("正在创建鱼塘。。");
        JSONObject jsonObject = new JSONObject();
        if (loginInfoService.getFlag(userId) == null || loginInfoService.getFlag(userId) == 0) {
            jsonObject.put("res", "permissionError");
            return jsonObject;
        }
        String path = UploadUtil.saveFile("pond", file, "image");
        if (path == null) {
            jsonObject.put("res", "non");
            return jsonObject;
        }
        if (path.equals("error")) {
            jsonObject.put("res", "false");
            return jsonObject;
        }
        FishPond fishPond = new FishPond(pondId, square, waterDepth, soil, bottomType, path);
        try {
            fishPondService.insertPond(fishPond);
            jsonObject.put("res", "success");
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("res", "false");
            return jsonObject;
        }
    }

    @PostMapping("/search_pond")
    public JSONObject searchPond(@RequestBody Map<String, Object> data) {
        JSONObject jsonObject = new JSONObject();
        String pondid = String.valueOf(data.get("pondid"));
        if (fishPondService.selectById(pondid) == null) {
            jsonObject.put("res", true);
        } else {
            jsonObject.put("res", false);
        }
        return jsonObject;
    }

    @GetMapping("/get_pondId")
    public List<String> getPondId() {
        List<String> idList = fishPondService.getId();
        return idList;
    }


    @PostMapping("/upload_excel")
    public JSONObject uploadExcel(@RequestParam("excel") MultipartFile file) {
        JSONObject jsonObject = new JSONObject();
        if (!file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            String prefix = fileName.substring(0, fileName.lastIndexOf('.'));
            String suffix = fileName.substring(fileName.lastIndexOf('.'));
            //这个判断可能写的并不好，如果有人恶意将后缀名改成 xls/xlsx，就会进行下一步
            if (!suffix.equals(".xls") && !suffix.equals(".xlsx")) {
                jsonObject.put("res", "parsingError");
                return jsonObject;
            }
            try {
                File tmpFile = File.createTempFile(prefix, suffix);

                file.transferTo(tmpFile);

                // 处理Excel文件上传逻辑
                List<HashMap<String, String>> list = new ArrayList<>();
                String table = excelAnalyze(tmpFile.getAbsolutePath(), list);
                //解析失败
                if (table.equals("")) {
                    jsonObject.put("res", "parsingError");
                    return jsonObject;
                }
                if (table.equals("DissolvedOxygen")) {
                    dissolvedOxygenService.insertList(list);
                } else if (table.equals("WaterFactor")) {
                    waterFactorService.insertList(list);
                } else {
                    weatherFactorService.insertList(list);
                }


//                Class<?> clazz = Class.forName("com.twxm.breed.service."+table+"Service");
//                Object obj = clazz.newInstance();
//                Method method = clazz.getDeclaredMethod("insertList", List.class);
//                method.invoke(obj,list);

                jsonObject.put("res", "true");
                return jsonObject;
            } catch (Exception e) {
                e.printStackTrace();
                jsonObject.put("res", "false");
                return jsonObject;
            }
        } else {
            jsonObject.put("res", "non");
            return jsonObject;
        }
    }

    @GetMapping("/get_ponds")
    public JSONArray getPonds(){
        JSONArray jsonArray = new JSONArray();
        List<FishPond> list = fishPondService.getAll();
        list.forEach(fishPond -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("pondid",fishPond.getPondId());
            jsonObject.put("soil",fishPond.getSoil());
            jsonObject.put("bottomtype",fishPond.getBottomType());
            jsonObject.put("square",fishPond.getSquare());
            jsonObject.put("waterdepth",fishPond.getWaterDepth());
            try {
                jsonObject.put("image",Base64Util.getBase64(fishPond.getImage()));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            jsonArray.add(jsonObject);
        });
        return jsonArray;
    }

    @PostMapping("/delete_ponds")
    public JSONObject deletePond(@RequestBody MyData data){
        JSONObject jsonObject = new JSONObject();
        List<String> list = data.getArray();
        for (String s:list){
            List<String> deviceInfoIdList = deviceInfoService.selectIdByPondId(s);
            try {
                deviceInfoService.deleteDevices(deviceInfoIdList);
                fishPondService.deleteById(s);
                jsonObject.put("res",200);
            } catch (ClientException e) {
                jsonObject.put("res",400);
            }
        }
        return jsonObject;
    }
}
